-- ModemListen.lua - 监听广播消息测试网络连接性
local component = require("component")
local event = require("event")

-- 检查是否有 modem
if not component.isAvailable("modem") then
    print("错误: 未找到 modem 组件")
    return
end

local modem = component.modem
modem.open(12345) -- 监听端口12345

print("Modem 监听测试程序")
print("正在监听端口 12345...")
print("按 Ctrl+C 退出")
print()

while true do
    local e = {event.pull()}

    if e[1] == "modem_message" then
        -- modem_message received from address:port:distance / ... / message
        local addr, port, dist, _, _, message = e[2], e[3], e[4], e[5], e[6], e[7]
        print(string.format("接收到消息 [%s]:%d (距离: %d) - %s",
                addr, port, dist, message))
    elseif e[1] == "interrupted" or (e[1] == "key_down" and e[4] == 3) then
        -- Ctrl+C 或中断
        break
    end
end

modem.close(12345)
print("程序已终止")
